# Author: Br. Francis Therese Krautter -- br.ftherese(at)gmail.com

# Notes: This module will not work unless you have lilypond installed (http://www.lilypond.org) along with an account on the lilypond posterous blog.  

# The cURL statement reads the username and password from the user's .netrc file in their home directory when accessing Posterous.

# Though you may not find lilypond useful or interesting, this module could be easily modified to produce other kinds of command-line generated content (pdf files, sound files, images, video) that is automatically posted (via Posterous) on the Web with the respective link posted in the IRC channel. 

package cringer::lilypond;

use Time::localtime;

# lilypond.pm
# provides search functionality for cringer using the Posterous API

our $VERSION = '2.0';

sub said{
 my $self = $_[0];
 my $args = $_[1];
 my $me = $self->{nick};

 unless($args->{body} =~ /^lily(music|pond|l||d|end|13): ?(.*)$/){ # if this isn't a lilypond query, we skip it.
  return;
 }

 my @r; 
 my $lilycommand = $1;
 my $lilydata = $2;
 $lilydata =~ s/system//g;
 if ($lilycommand eq "") {
  my $lilydataesc = $self->{d}->quote($lilydata);
  my $rows = $self->{d}->do("INSERT INTO lilypond_code ( nick, code ) VALUES ( '$args->{who}', $lilydataesc )"); 
  return $rows. " line ok"; 
 }
 if ($lilycommand eq "d"){
  if ($lilydata ne ""){
   $self->{d}->do("DELETE FROM lilypond_code WHERE nick = '$args->{who}' ORDER BY time DESC LIMIT $lilydata"); return $lilydata . " lines deleted."}
  else {$self->{d}->do("DELETE FROM lilypond_code WHERE nick = '$args->{who}' ORDER BY time DESC LIMIT 1"); return "1 line deleted.";}
 }
 if ($lilycommand eq "l"){
  my $code = $self->{d}->prepare( "SELECT ( code ) FROM lilypond_code WHERE nick = '$args->{who}' ORDER BY time");
  my $rows = $code->execute();
  while (my $line = $code->fetchrow_array) {
    push(@r, $line);}
  push(@r, $rows. " lines ok");
  return @r;
 }
 if (($lilycommand eq "end")|| ($lilycommand eq "13")){
  my $lilydataesc = $self->{d}->quote($lilydata);
  $self->{d}->do("INSERT INTO lilypond_code ( nick, code ) VALUES ( '$args->{who}', $lilydataesc )");
  $lilydata = "";
  my $code = $self->{d}->prepare( "SELECT ( code ) FROM lilypond_code WHERE nick = '$args->{who}' ORDER BY time");
  $code->execute();
  while (my $line = $code->fetchrow_array) {
   $lilydata .= $line . "\n";}
#  $self->{d}->do("DELETE FROM lilypond_code WHERE nick = '$args->{who}'");
 }
 @now = split /\s/, ctime();
 my $filename = "$now[3]$now[4]";
 $filename =~ s/:/-/g;

 open FILE, ">/tmp/$filename\.ly" or die $!;
 if ($lilycommand ne "13"){print FILE '\\version "2.12.2"';} else {print FILE '\\version "2.13.17"';}
 print FILE "\n";

 # print FILE "\\header { tagline = ##f } \n"; --not needed if you comment it out in your lily-init scripts.

 if ($lilycommand eq "music"){print FILE "\\score { \n";}
 print FILE "\t" . $lilydata . "\n";
 if ($lilycommand eq "music"){print FILE "\t\\midi {} \n";}
 if ($lilycommand eq "music"){print FILE "\t\\layout {} \n }";}
 close FILE;

 if ($lilycommand ne "13") { my $result = `lilypond -dbackend=eps -dno-gs-load-fonts -dinclude-eps-fonts --png '/tmp/$filename.ly' 2>&1`;}
 else{ my $result = `/home/ltsp5/bin/lilypond -dbackend=eps -dno-gs-load-fonts -dinclude-eps-fonts --png '/tmp/$filename.ly' 2>&1`;}
 # print $result;

 my $htmlresults = `cat /tmp/$filename.ly` . "\n\n" . $result;
 $htmlresults =~ s/([^\&])([<])/$1\&lt;/g; 
 $htmlresults =~ s/([^\&])([>])/$1\&gt;/g; 
 $htmlresults =~ s/[\n\r]/<br\/>/gs;
 $htmlresults =~ s/([^\\])(["`])/$1\\$2/g; 
 print $htmlresults;

 my $curlrequest;

 if ($lilycommand eq "music"){
 system("timidity -Ow $filename.midi");
 system("lame -h -V9 $filename.wav $filename.mp3");

# This curl request assumes that you have the proper username and password in your .netrc file

 $curlrequest = qq~curl -D - -n -F "site_id=1147841" -F "autopost=0" -F "title=$filename" -F "media[2]=\@$filename.mp3" -F "media[0]=\@$filename.png" -F "body=$htmlresults" http://posterous.com/api/newpost~; }
 else {$curlrequest = qq~curl -D - -n -F "site_id=1147841" -F "autopost=0" -F "title=$filename" -F "media[0]=\@$filename.png" -F "body=$htmlresults" http://posterous.com/api/newpost~; }

 `$curlrequest`;
  system("rm *.png *.eps *.tex* *.count /tmp/*.ly");
 if ($lilycommand eq "music"){system("rm *.midi *.mp3 *.wav /tmp/*.ly");}

 push(@r, qq~lilypond file "$filename.ly" at http://lilypond.posterous.com/$filename~);
return @r;}
